package net.hserver.sockt;

import net.hserver.socket.common.HSocketContext;
import net.hserver.socket.common.Handler;
import net.hserver.socket.server.HSocketServer;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.charset.StandardCharsets;

public class HttpServer {

    public static void main(String[] args) {
        new HSocketServer(8888).addHandler(new Handler() {
            private String generateResponse(String message) {
                return "HTTP/1.1 200 OK\r\n" +
                        "Content-type:text/html\r\n" +
                        "Connection:keep-alive\r\n" +
                        "Content-Length:" + message.length() + "\r\n" +
                        "\r\n" +
                        message;
            }
            @Override
            public void onConnect(HSocketContext channel) {

            }

            @Override
            public void onMessage(HSocketContext channel, byte[] data) {
                try {
                    channel.write((generateResponse("ok")).getBytes(StandardCharsets.UTF_8));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(HSocketContext channel, Throwable throwable) {
                System.out.println("异常："+throwable.getMessage());
            }
        }).start();
    }
}
